<template>
  <a-modal :title="isEdit ? '编辑' : '新增'" :width="720" :visible="visible" @ok="handleModalConfirm"
    @cancel="handleModalCancel" :confirm-loading="modalLoading">
    <a-form-model ref="form" :model="form" :rules="formRules" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
      <a-form-model-item label="产品名称" prop="productName">
        <a-input v-model="form.productName" placeholder="请输入" allowClear />
      </a-form-model-item>
      <a-form-model-item label="产品昵称" prop="productNike">
        <a-input v-model="form.productNike" placeholder="请输入" allowClear />
      </a-form-model-item>
      <a-form-model-item label="公司名称" prop="companyName">
        <a-input v-model="form.companyName" placeholder="请输入" allowClear />
      </a-form-model-item>
      <a-form-model-item label="产品类型" prop="productType">
        <a-select v-model="form.productType" :options="productOptions" placeholder="请选择" allowClear></a-select>
      </a-form-model-item>
      <a-form-model-item label="产品链接">
        <a-input v-model="form.productUrl" placeholder="请输入" allowClear />
      </a-form-model-item>
      <a-form-model-item label="周期">
        <a-input v-model="form.loanCycle" placeholder="请输入" allowClear />
      </a-form-model-item>
      <a-form-model-item label="利率">
        <a-input v-model="form.rate" placeholder="请输入" allowClear />
      </a-form-model-item>
      <a-form-model-item label="标签">
       <div style="display: flex;">
        <a-input v-model="form.tips" placeholder="请输入后回车，支持输入多个标签" @keyup.enter="onEnter" />
        <a-button @click="onEnter">确认</a-button>
       </div>
        <div class="tags-wrap">
          <div  class="wrap_tag" :key="index" v-for="(item, index) in tags" style="background-color: #ecf7fe; padding: 0px 10px; color: skyblue; margin-right: 10px; height: 25px; line-height: 25px; " @click="onClose(index)">{{ item
            }} x</div>
        </div>
      </a-form-model-item>
      <a-form-model-item label="产品最高可借额度">
        <a-input v-model="form.loanQuota" placeholder="请输入" allowClear />
      </a-form-model-item>
      <a-form-model-item label="图标">
        <a-upload name="file" :action="uploadUrl" accept="image/*" :file-list="fileList" :headers="{ Authorization }"
          list-type="picture-card" @change="handleChange" @preview="handlePreview">
          <a-icon v-if="fileList.length < 1" type="plus" />
          <div v-if="fileList.length < 1" class="ant-upload-text">请选择图片</div>
        </a-upload>
      </a-form-model-item>
      <a-form-model-item label="贷超价格" prop="price">
        <a-input-number v-model="form.price" :min="0" placeholder="请输入" style="width: 100%" />
      </a-form-model-item>
      <a-form-model-item label="权重" prop="weight">
        <a-input-number v-model="form.weight" :min="0" placeholder="请输入" style="width: 100%" />
      </a-form-model-item>
      <a-form-model-item label="贷超推送类型" prop="pushType">
        <a-select v-model="form.pushType" :options="pushOptions" placeholder="请选择" allowClear></a-select>
      </a-form-model-item>
      <a-form-model-item label="限制条数">
        <a-input-number v-model="form.limitingNum" :min="0" placeholder="请输入" style="width: 100%" />
      </a-form-model-item>
      <a-form-model-item label="handlerCode">
        <a-input v-model="form.handlerCode" :min="0" placeholder="请输入" style="width: 100%" />
      </a-form-model-item>
      <a-form-model-item label="限制时间">
        <a-time-picker v-model="startTime" format="HH:mm" valueFormat="HH:mm" placeholder="开始时间" />
        <span style="margin:0 12px;color:rgba(0, 0, 0, 0.65)">—</span>
        <a-time-picker v-model="endTime" format="HH:mm" valueFormat="HH:mm" placeholder="结束时间" />
      </a-form-model-item>
      <a-form-model-item label="限制开关">
        <a-switch v-model="form.limitingSwitch" checked-children="开启" un-checked-children="关闭" style="width:100px" />
      </a-form-model-item>
      <a-form-model-item label="启用状态">
        <a-switch v-model="form.status" checked-children="开启" un-checked-children="关闭" style="width:100px" />
      </a-form-model-item>
    </a-form-model>
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img style="width: 100%" :src="previewImage" />
    </a-modal>
  </a-modal>
</template>

<script>
import * as Ajax from '@/api/loan';
import config from '@/utils/config';
export default {
  props: {
    visible: {
      type: Boolean,
    },
    default: {
      type: Object,
      default: () => { },
    },
  },
  data() {
    return {
      startTime: '',
      endTime: '',
      modalLoading: false,
      form: {
        productName: '',
        productNike: '',
        productType: undefined,
        productUrl: '',
        price: '',
        weight: '',
        pushType: undefined,
        limitingNum: '',
        limitingSwitch: false,
        timingTime: [],
        status: false,
      },
      formRules: {
        companyName: { required: true, message: '请输入公司名称', trigger: ['blur', 'change'] },
        productName: { required: true, message: '请输入产品名称', trigger: ['blur', 'change'] },
        productNike: { required: true, message: '请输入产品昵称', trigger: ['blur', 'change'] },
        productType: { required: true, message: '请选择产品类型', trigger: ['blur', 'change'] },
        pushType: { required: true, message: '请选择产品推送类型', trigger: ['blur', 'change'] },
        price: { required: true, message: '请输入产品价格', trigger: ['blur', 'change'] },
        weight: { required: true, message: '请输入权重', trigger: ['blur', 'change'] },
      },
      productOptions: [
        { label: 'api', value: 0 },
        { label: '产品', value: 1 },
      ],
      pushOptions: [
        { label: '联登进件', value: 0 },
        { label: 'h5链接', value: 1 },
        { label: '全流程', value: 2 },
        { label: '半流程', value: 3 },
      ],
      fileList: [],
      Authorization: localStorage.Authorization || '',
      uploadUrl: config.apiHost + '/web/sys/file/upload',
      previewVisible: false,
      previewImage: '',
      tags: [],
    };
  },
  computed: {
    isEdit() {
      return Object.keys(this.default).length > 0;
    },
  },
  watch: {
    visible(val) {
      if (val) {
        if (this.isEdit) {
          this.form = JSON.parse(JSON.stringify(this.default));
          if (this.form.icon) {
            this.fileList = [
              {
                uid: '-1',
                name: 'image.png',
                status: 'done',
                url: this.form.icon,
              },
            ];
          }
          const time = this.form.timingTime.split('-');
          this.startTime = time?.[0] || '';
          this.endTime = time?.[1] || '';
          if(this.form.tips){

            this.tags = this.form.tips.split(',');
          }else {
            this.tags = []
          }
          
          
          this.form.tips = '';
        }
      } else {
        // this.handleModalCancel();
      }
    },
  },
  methods: {
    onEnter() {
      if (this.form.tips && this.form.tips.trim()) {
        this.tags.push(this.form.tips);
        this.form.tips = '';
      } else {
        this.$message.error('不能为空');
      }
    },
    onClose(index) {
      // console.log(this.tags)
      this.tags.splice(index ,1);
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
      });
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({ file, fileList }) {
      this.fileList = fileList;
    },
    handleModalConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log(this.tags)
          this.modalLoading = true;
          const params = { ...this.form };
          params.tips = this.tags.join(',');
          params.limitingSwitch = params.limitingSwitch ? 1 : 0;
          params.status = params.status ? 0 : 1;
          params.timingTime = this.startTime && this.endTime ? this.startTime + '-' + this.endTime : '';
          params.icon = this.fileList?.[0]?.response?.data || this.fileList?.[0]?.url || '';
          const ajaxName = this.isEdit ? 'editConfigList' : 'addConfigList';
          const message = this.isEdit ? '编辑成功' : '新增成功';
          Ajax[ajaxName](params)
            .then(({ success }) => {
              if (success) {
                this.$message.success(message);
                this.$emit('success');
                this.handleModalCancel();
              }
            })
            .finally(() => {
              this.modalLoading = false;
            });
        }
      });
    },
    handleModalCancel() {
      this.fileList = [];
      this.tags = [];
      this.form = this.$options.data().form;
      this.$refs.form.resetFields();
      this.$emit('close');
    },
  },
};
</script>

<style lang="scss" scoped>
.table-wrap {
  margin-top: 20px;
  padding-top: 16px;
}

.btn-gruop {
  display: flex;
  justify-content: flex-end;
}

::v-deep .ant-form-item {
  &:last-child {
    margin-bottom: 0;
  }
}

.tags-wrap {
  display: flex;
  flex-wrap: wrap;
  margin-top: 6px;
 
}
.wrap_tag{
  cursor: pointer;
}

::v-deep .ant-tag {
  margin-bottom: 6px;
}
</style>
